import datetime
import os
import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
    'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
}
# url
gamed = 'https://apps.game.qq.com/lol/match/apis/searchBMatchInfo_bak.php?p8=5&p1=148&p4=3&p9=&p10=&p6=2&p11=&p12=&page=1&pagesize=100'
url = 'https://apps.game.qq.com/lol/match/apis/searchBMatchInfo_bak.php?p8=5&p1=148&p4=1&p9=&p10=&p6=3&p11=&p12=&page=1&pagesize=100'


class Event:
    """
    事件对象
    """

    def __init__(self, kwargs):
        self.event_data = kwargs

    def __turn_to_string__(self):
        self.event_text = "BEGIN:VEVENT\n"
        EDG = ""
        for item, data in self.event_data.items():
            item = str(item).replace("_", "-")
            if item == "EDG":
                EDG = data
                continue
            if item not in ["ORGANIZER", "DTSTART", "DTEND"]:
                self.event_text += "%s:%s\n" % (item, data)
            else:
                self.event_text += "%s;%s\n" % (item, data)
        if len(EDG) != 0:
            self.event_text += "BEGIN:VALARM\n"
            self.event_text += "TRIGGER:-PT5M\n"
            for item, data in self.event_data.items():
                item = str(item).replace("_", "-")
                if item == "UID":
                    self.event_text += "%s:%s\n" % (item, data)
            self.event_text += "ATTACH;VALUE=URI:Chord\n"
            self.event_text += "ACTION:AUDIO\n"
            self.event_text += "END:VALARM\n"
        self.event_text += "END:VEVENT\n"
        return self.event_text


class Calendar:
    """
    日历对象
    """

    def __init__(self, calendar_name="My Calendar"):
        self.__events__ = {}
        self.__event_id__ = 0
        self.calendar_name = calendar_name

    def add_event(self, **kwargs):
        event = Event(kwargs)
        event_id = self.__event_id__
        self.__events__[self.__event_id__] = event
        self.__event_id__ += 1
        return event_id

    def modify_event(self, event_id, **kwargs):
        for item, data in kwargs.items():
            self.__events__[event_id].event_data[item] = data

    def remove_event(self, event_id):
        self.__events__.pop(event_id)

    def get_ics_text(self):
        self.__calendar_text__ = """BEGIN:VCALENDAR\nPRODID:-//ZHONG_BAI_REN//APPGENIX-SOFTWARE//\nVERSION:2.0\nCALSCALE:GREGORIAN\nMETHOD:PUBLISH\nX-WR-CALNAME:%s\nX-WR-TIMEZONE:null\n""" % self.calendar_name
        for key, value in self.__events__.items():
            self.__calendar_text__ += value.__turn_to_string__()
        self.__calendar_text__ += "END:VCALENDAR"
        return self.__calendar_text__

    def save_as_ics_file(self):
        ics_text = self.get_ics_text()
        open("./%s.ics" % self.calendar_name, "w", encoding="utf8").write(
            ics_text)  # 使用utf8编码生成ics文件，否则日历软件打开是乱码

    def open_ics_file(self):
        os.system("./%s.ics" % self.calendar_name)


def add_event(cal, SUMMARY, DTSTART, DTEND, DESCRIPTION, LOCATION):
    """
    向Calendar日历对象添加事件的方法
    :param cal: calender日历实例
    :param SUMMARY: 事件名
    :param DTSTART: 事件开始时间
    :param DTEND: 时间结束时间
    :param DESCRIPTION: 备注
    :param LOCATION: 时间地点
    :return:
    """
    time_format = "TZID=Asia/Shanghai:{date.year}{date.month:0>2d}{date.day:0>2d}T{date.hour:0>2d}{date.minute:0>2d}00"
    dt_start = time_format.format(date=DTSTART)
    dt_end = time_format.format(date=DTEND)
    create_time = datetime.datetime.today().strftime("%Y%m%dT%H%M%SZ")
    EDG = ""
    if "EDG" in SUMMARY:
        EDG = "EDG"
    cal.add_event(
        SUMMARY=SUMMARY,
        ORGANIZER="CN=Cao HongHai:mailto:caohonghai@caohonghai.com",
        DTSTART=dt_start,
        DTEND=dt_end,
        DTSTAMP=create_time,
        UID="{}".format(datetime.datetime.now().timestamp()),
        SEQUENCE="0",
        CREATED=create_time,
        DESCRIPTION=DESCRIPTION,
        LAST_MODIFIED=create_time,
        LOCATION=LOCATION,
        STATUS="CONFIRMED",
        TRANSP="OPAQUE",
        EDG=EDG
    )


if __name__ == '__main__':
    calendar = Calendar(calendar_name="test")
    
    # 结束的
    t = requests.get(url=gamed, headers=headers)  # 请求网址
    t.encoding = 'gbk'
    text = t.text
    SUMMARY =""
    game = eval(text)
    for item in game['msg']['result']:
        if "EDG" in item['GameTypeName']:
            SUMMARY = item['GameTypeName'] + " " + item['bMatchName'] + " 😊"
        else:
            SUMMARY = item['GameTypeName'] + " " + item['bMatchName']
        add_event(calendar,
            SUMMARY=SUMMARY,
              DTSTART=datetime.datetime(
                  year=int(item['MatchDate'][0:4]), month=int(item['MatchDate'][5:7]), day=int(item['MatchDate'][8:10]), hour=int(item['MatchDate'][11:13]), minute=int(item['MatchDate'][14:16]), second=int(item['MatchDate'][17:19])),
              DTEND=datetime.datetime(
                  year=int(item['MatchDate'][0:4]), month=int(item['MatchDate'][5:7]), day=int(item['MatchDate'][8:10]), hour=int(item['MatchDate'][11:13]) + 2, minute=int(item['MatchDate'][14:16]), second=int(item['MatchDate'][17:19])),
              DESCRIPTION=item['GameTypeName'] + " " + item['bMatchName'] + " " + item['ScoreA'] + ":" + item['ScoreB'],
              LOCATION=item['bMatchName'] + " " + item['ScoreA'] + ":" + item['ScoreB'])

    # 未开始的
    t = requests.get(url=url, headers=headers)  # 请求网址
    t.encoding = 'gbk'
    text = t.text
    game = eval(text)
    for item in game['msg']['result']:
        if "EDG" in item['GameTypeName']:
            SUMMARY = item['GameTypeName'] + " " + item['bMatchName'] + "😊"
        else:
            SUMMARY = item['GameTypeName'] + " " + item['bMatchName']
        add_event(calendar,
            SUMMARY=SUMMARY,
            DTSTART=datetime.datetime(
                year=int(item['MatchDate'][0:4]), month=int(item['MatchDate'][5:7]), day=int(item['MatchDate'][8:10]), hour=int(item['MatchDate'][11:13]), minute=int(item['MatchDate'][14:16]), second=int(item['MatchDate'][17:19])),
            DTEND=datetime.datetime(
                year=int(item['MatchDate'][0:4]), month=int(item['MatchDate'][5:7]), day=int(item['MatchDate'][8:10]), hour=int(item['MatchDate'][11:13]) + 2, minute=int(item['MatchDate'][14:16]), second=int(item['MatchDate'][17:19])),
            DESCRIPTION=item['GameTypeName'] + " " + item['bMatchName'],
            LOCATION=item['GameTypeName'] + " " + item['bMatchName'] )
    
    print("yes")
    # print(calendar.get_ics_text())
    calendar.save_as_ics_file()
